package ru.averta.notes.service.interceptor;

import org.hibernate.EmptyInterceptor;
import org.hibernate.Interceptor;
import org.hibernate.type.Type;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

/**
 * <code>SiteDeleteInterceptor</code>
 * <p/>
 * Класс собирает набор интерсепторов
 * В случае возникновения события проходится по всем интерсепторам в коллекции
 *
 * @author fedor.belov (fedor.belov@mail.ru)
 *         Date: 16.09.11 17:15
 */
public class MainInterceptor extends EmptyInterceptor {

    private List<Interceptor> interceptors = new LinkedList<Interceptor>();

    /**
     * Добавляет новый интерсептор в коллекцию
     *
     * @param interceptor
     */
    public void addInterceptor(Interceptor interceptor) {
        interceptors.add(interceptor);
    }

    @Override
    public void onDelete(
            Object entity,
            Serializable id,
            Object[] state,
            String[] propertyNames,
            Type[] types) {

        for (Interceptor interceptor : interceptors) {
            interceptor.onDelete(entity, id, state, propertyNames, types);
        }

    }

    @Override
    public boolean onFlushDirty(
            Object entity,
            Serializable id,
            Object[] currentState,
            Object[] previousState,
            String[] propertyNames,
            Type[] types) {

        boolean answer = true;

        for (Interceptor interceptor : interceptors) {
            answer = (answer && interceptor.onFlushDirty(entity, id, currentState, previousState, propertyNames, types));
        }

        return answer;
    }

    @Override
    public boolean onLoad(
            Object entity,
            Serializable id,
            Object[] state,
            String[] propertyNames,
            Type[] types) {

        boolean answer = true;

        for (Interceptor interceptor : interceptors) {
            answer = (answer && interceptor.onLoad(entity, id, state, propertyNames, types));
        }

        return answer;
    }

    @Override
    public boolean onSave(
            Object entity,
            Serializable id,
            Object[] state,
            String[] propertyNames,
            Type[] types) {

        boolean answer = true;

        for (Interceptor interceptor : interceptors) {
            answer = (answer && interceptor.onSave(entity, id, state, propertyNames, types));
        }

        return answer;
    }

}
